import 'package:dmz/base/controller/base_controller.dart';

import 'package:dmz/business/home/controller/set_purchase_controller.dart';
import 'package:dmz/business/home/model/ebike_set.dart';
import 'package:dmz/business/home/model/moto_model.dart';
import 'package:dmz/business/home/widgets/set_moto_widgets.dart';
import 'package:dmz/request/apis.dart';
import 'package:dmz/request/request_client.dart';
import 'package:dmz/routers/routers.dart';
import 'package:dmz/tools/blue/blue_business.dart';
import 'package:dmz/tools/blue/blue_config.dart';
import 'package:dmz/tools/map/map_manger.dart';
import 'package:dmz/utils/customize_loding.dart';
import 'package:flutter/widgets.dart';
import 'package:get/get.dart';
import 'home_main_controller.dart';

class SetMotoController extends BaseController {
  MotoModel? data;
  List<String> mainTitles = [
    '车辆名称'.tr,
    '用车分享'.tr,
    '智能配置'.tr,
    '运行信息'.tr,
    '车辆信息'.tr,
    '智能服务'.tr
  ];
  int shareNum = 0;
  TextEditingController inputController = TextEditingController();
  EbikeSet ebikeSet = EbikeSet();
  var strs = ['低'.tr, '中'.tr, '高'.tr];
  var strsOther = ['近'.tr, '中'.tr, '远'.tr];
  FixedExtentScrollController lowPowerController =
      FixedExtentScrollController();
  FixedExtentScrollController timeSelectController =
      FixedExtentScrollController();
  int lowPowerIndex = 0;
  String endDate = '';
  int serviceStatus = 0;
  @override
  void loadNet() {}

  @override
  void onHidden() {}

  @override
  void onReady() {
    super.onReady();
    var homeController = Get.find<HomePageController>();
    data = homeController.motoList[homeController.pageIndex];
    homeController.showBottom = false;
    homeController.defaultBottom = false;
    homeController.forceBottom = false;
    inputController.text = data?.name ?? '';
    getShareList();
    getServiceStatus();
    update(['setMainList']);
  }

  void getShareList() {
    RequestClient().post<Map>(APIS.shareDeviceList,
        data: {'ebike_id': data?.id, 'type': 0}).then((value) {
      if (value != null) {
        data?.shareTotal = value['total'] ?? 0;
      }
      update(['setMainList']);
    });
  }

  mainTurnOtherPage(int index) {
    switch (index) {
      case 0:
        Get.toNamed(RouteGet.changeName);
        break;
      case 1:
        Get.toNamed(RouteGet.shareKey, arguments: data);
        break;
      case 2:
        Get.toNamed(RouteGet.changeParms);
        break;
      case 3:
        Get.toNamed(RouteGet.setOperation);
        break;
      case 4:
        Get.toNamed(RouteGet.setMotoInfor);
        break;
      case 5: //智能服务
        if (serviceStatus != 1) Get.toNamed(RouteGet.purchase);
        break;
      default:
    }
  }

  ///锁定车辆
  lockVehicle() {
    if ((data?.lock_status ?? 0) == 1) {
      EMILoding.showBottomWindow(SetMotoWidgets.hitBottomWidget((bool agree) {
        Get.back();
        if (!agree) return;
        didNextAction();
      }));
    } else {
      didNextAction();
    }
  }

  ///下一步操作
  didNextAction() {
    if (data?.contentBlue ?? false) {
      //蓝牙操作
      EMIBlueBusiness.deviceOperate(data!.sn_code!, EMIBlueACT.lockStatusChange,
          sensitive: data?.lock_status ?? 0, callback: (String content) {
        debugPrint('蓝牙回调 ---  $content');
        if (content == '01') {
          lockScuess();
        }
      });

      return;
    }
    //4g操作
    RequestClient().post(APIS.sendCmd, data: {
      'ebike_id': data?.id,
      'cmd': (data?.lock_status ?? 0) == 1 ? 0 : 1
    }).then((value) {
      lockScuess();
    });
  }

  ///操作成功
  lockScuess() {
    data?.lock_status = data?.lock_status == 0 ? 1 : 0;
    EMILoding.hitLoding(data?.lock_status == 0 ? '解锁成功'.tr : '锁定成功'.tr,
        isScuess: true);
    Get.back();
  }

  ///保存名字
  saveName() {
    if (inputController.text.isEmpty || inputController.text == data?.name) {
      return EMILoding.hitLoding('请输入新的车辆名称'.tr);
    }
    RequestClient().post(APIS.changeInfor, data: {
      'ebike_id': data?.id,
      'ebike_name': inputController.text
    }).then((value) {
      EMILoding.hitLoding('修改成功'.tr);
      data?.name = inputController.text;
      update(['setMainList']);
      Get.back();
    });
  }

  getSettingInfor() {
    RequestClient().post<Map>(APIS.getSetting, data: {
      'ebike_id': data?.id,
      'size': 1,
      'index': 1,
    }).then((value) async {
      ebikeSet = EbikeSet.fromJson(value?['ebike_set'] as Map<String, dynamic>);
      ebikeSet.fly_car = value?['fly_car'] ?? 0;
      ebikeSet.id = value?['ebike_id'] ?? 0;
      ebikeSet.latLng = await EMIMapManger().convertLatLng(
          ebikeSet.fence_center?['lng'], ebikeSet.fence_center?['lat']);
      update(['parmsList']);
      debugPrint('智能配置 --- $value');
    });
  }

  parmsClick(int type, {int? otherData}) {
    switch (type) {
      case 0: //低电量报警
        lowPowerIndex = (ebikeSet.power_value ?? 0) ~/ 10 - 1;
        lowPowerController =
            FixedExtentScrollController(initialItem: lowPowerIndex);
        EMILoding.showBottomWindow(
            SetMotoWidgets.bottomListWheelScrollView(true),
            isDismissible: true,
            showBack: true);
        break;
      case 1: //电子围栏
        Get.toNamed(RouteGet.map);
        break;
      case 2: //自动锁车
        lowPowerIndex = (ebikeSet.leave_countdown ?? 0) ~/ 60 - 1;
        timeSelectController =
            FixedExtentScrollController(initialItem: lowPowerIndex);
        EMILoding.showBottomWindow(
            SetMotoWidgets.bottomListWheelScrollView(false),
            isDismissible: true,
            showBack: true);
        break;
      case 3: //蓝牙靠近解锁
        chageBlueLock(otherData: otherData);
        break;
      case 4: //乘坐感应
        setRideSensing();
        break;
      case 5: //震动报警灵敏度设置
        setAlarmSensitivity(otherData ?? 0);
        break;
      case 6: //故障反馈
        upDataProplem();
        break;
      case 7: //安全警报
        securityAlarm();
        break;
      default:
    }
  }

  ///滚轮滚动
  listWheelChange(int index, bool isProw) {
    debugPrint('低电量选择 ---000 ');
    lowPowerIndex = index;
    update(['setlistWheel']);
  }

  ///低电量选择
  changeLowPower(bool isProw) {
    debugPrint('低电量选择 ---111');
    Get.back();
    if (isProw) {
      ebikeSet.power_value = (lowPowerIndex + 1) * 10;
    } else {
      // ebikeSet.leave_countdown = (lowPowerIndex + 1) * 60;
      sendSetUpData('auto_lock_time',
          type: EMIBlueACT.autoLock, otherData: lowPowerIndex + 1, scuess: () {
        ebikeSet.leave_countdown = (lowPowerIndex + 1) * 60;
        update(['parmsList']);
      });
    }
  }

  ///蓝牙靠近解锁
  chageBlueLock({int? otherData}) {
    if (!data!.contentBlue) {
      return EMILoding.hitLoding('请先配对蓝牙'.tr);
    }
    if (otherData == null) {
      sendSetUpData('senseless_unlock',
          type: EMIBlueACT.bleUnlockDistance,
          otherData: ebikeSet.open_lock == 1 ? 0 : 1, scuess: () {
        ebikeSet.open_lock = ebikeSet.open_lock == 1 ? 0 : 1;
        update(['parmsList']);
      });
    } else {
      debugPrint('蓝牙靠近解锁2 --- $otherData');
      sendSetUpData('senseless_unlock',
          type: EMIBlueACT.bleUnlockDistance,
          otherData: otherData + 1,
          otherKey: 'open_lock',
          otherKeyData: 1, scuess: () {
        ebikeSet.open_lock_distance = otherData + 1;
        update(['parmsList']);
      });
    }
  }

  ///乘坐感应操作
  setRideSensing() {
    sendSetUpData('prevent_out_of_control',
        otherData: ebikeSet.fly_car == 1 ? 0 : 1, onlyNet: true, scuess: () {
      ebikeSet.fly_car = ebikeSet.fly_car == 1 ? 0 : 1;
      update(['parmsList']);
    });
  }

  ///震动灵敏度
  setAlarmSensitivity(int otherData) {
    sendSetUpData('vibration_sensitivity',
        type: EMIBlueACT.vibrateSensitive,
        otherData: otherData + 1,
        onlyNet: true, scuess: () {
      ebikeSet.vibration_sensitivity = otherData + 1;
      update(['parmsList']);
    });
  }

  ///故障反馈
  upDataProplem() {
    sendSetUpData('ebike_set',
        type: EMIBlueACT.vibrateSensitive,
        otherData: {'hitchs_up': ebikeSet.vibration_sensitivity == 1 ? 0 : 1},
        onlyNet: true, scuess: () {
      ebikeSet.vibration_sensitivity =
          ebikeSet.vibration_sensitivity == 1 ? 0 : 1;
      update(['parmsList']);
    });
  }

  ///安全报警
  securityAlarm() {
    sendSetUpData('ebike_set',
        type: EMIBlueACT.vibrateSensitive,
        otherData: {'alarm': ebikeSet.alarm == 1 ? 0 : 1},
        onlyNet: true, scuess: () {
      ebikeSet.alarm = ebikeSet.alarm == 1 ? 0 : 1;
      update(['parmsList']);
    });
  }

  ///上传设置设置数据
  sendSetUpData(String key,
      {EMIBlueACT? type,
      String? otherKey,
      int? otherKeyData,
      dynamic otherData,
      bool onlyNet = false,
      Function()? scuess}) {
    debugPrint('当前状态 --- ${data?.online_status} ');
    if ((data?.contentBlue ?? false) && !onlyNet) {
      EMIBlueBusiness.deviceOperate(data?.sn_code ?? '', type!,
          otherData: otherData, callback: (String content) {
        if (content == '01') {
          scuess != null ? scuess() : null;
        }
      });
    } else {
      RequestClient()
          .post(APIS.setSetting,
              data: otherKey != null
                  ? {
                      'ebike_id': data?.id,
                      key: otherData,
                      otherKey: otherKeyData
                    }
                  : {
                      'ebike_id': data?.id,
                      key: otherData,
                    })
          .then((value) {
        debugPrint('智能配置设置 --- $value');
        scuess != null ? scuess() : null;
      });
    }
  }

  ///服务有效期
  getServiceStatus() {
    RequestClient().post<Map>(APIS.serviceStatus, data: {
      'ebike_id': data?.id ?? 0,
    }).then((value) {
      endDate = value?['end_date'] ?? '';
      serviceStatus = value?['status'] ?? 0;
      update(['setMainList']);
    });
  }
}

class SetMotoBinding extends Bindings {
  @override
  void dependencies() {
    Get.lazyPut(() => SetPurchaseController());
    Get.lazyPut(() => SetMotoController(), fenix: true);
  }
}
